<?php
include_once('Smarty.class.php');
$main_smarty = new Smarty;

include_once('config.php');
include_once(mnminclude.'html1.php');
include_once(mnminclude.'ts.php');
include_once(mnminclude.'utils.php');
include_once(mnminclude.'user.php');
include_once(mnminclude.'link.php');
include_once(mnminclude.'tags.php');
include_once(mnminclude.'hunt.php');
include_once(mnminclude.'search.php');
include_once(mnminclude.'KMessaging.php');
include_once(mnminclude.'smartyvariables.php');

// html tags allowed during submit
$main_smarty->assign('Story_Content_Tags_To_Allow', htmlspecialchars(Story_Content_Tags_To_Allow));

// breadcrumbs and page titles

$navwhere['text1'] = $main_smarty->get_config_vars('PLIGG_Visual_Breadcrumb_Submit');
$navwhere['link1'] = getmyurl('submit', '');
$main_smarty->assign('navbar_where', $navwhere);
$main_smarty->assign('posttitle', " / " . '寻人');

$main_smarty = do_sidebar($main_smarty);

// make sure user is logged in
//force_authentication(); do not need to authenticate at the beginning

define('pagename', 'human_hunt'); 
$main_smarty->assign('pagename', pagename);

if (isset($_REQUEST['view'])) {
	$view = $_REQUEST['view'];
}
else {
	$view = 'hunts';
}

switch ($view) {
	case 'hunts':
		$doing = "show_hunts";
		define(doing,$doing);
		$main_smarty->assign('doing',doing);
		show_hunts();
		break;
	case 'owner_hunt': 
		$doing = "owner_hunt";
		define(doing,$doing);
		$main_smarty->assign('doing',doing);
		owner_hunt();
		break;
	case 'user_hunt': 
		$doing = "user_hunt";
		define(doing,$doing);
		$main_smarty->assign('doing',doing);
		user_hunt();
		break;
	case 'edit_newhunt':
		$doing = "edit_newhunt";
		define(doing,$doing);
		$main_smarty->assign('doing',doing);
		edit_newhunt();
		break;
	case 'modify_hunt':
		$doing = "modify_hunt";
		define(doing,$doing);
		$main_smarty->assign('doing',doing);
		modify_hunt();
		break;
	default:
		$doing = "show_hunts";
		define(doing,$doing);
		$main_smarty->assign('doing',doing);
		show_hunts();
		break;
}

exit;

function owner_hunt() {
	global $main_smarty, $db, $dblang, $current_user, $the_template, $top_users_size, $offset, $rows, $doing, $reco_offset, $reco_rows;
	
	//deal the search
	if (isset($_POST['key'])) {
		$main_smarty->assign('key',$_POST['key']);
		$main_smarty->assign('reco_cur_page',reco_get_current_page());
		if (trim($_POST['key']) != '') {
			$reco_offset=(reco_get_current_page()-1)*$top_users_size;
			$sqlquery = "SELECT COUNT(" . table_links . ".link_id) FROM " . table_links . " WHERE ".table_links .".link_category=" .get_category_id("物") . " AND " . table_links . ".link_title LIKE '%".$_POST["key"]."%'" . " AND NOT EXISTS ( SELECT * FROM " . table_link_owner . " WHERE " . table_link_owner .".link_id = " . table_links . ".link_id)";
			$reco_rows = $db->get_var($sqlquery);
			if (!($reco_offset<$reco_rows)) {
				$reco_offset = 0;//in case the user change the keyword to search
				$main_smarty->assign('reco_cur_page',1);
				$_POST['reco_page'] = 1;//so will not get wrong location
			}
			if ($reco_rows>0) {
				$sqlquery = "SELECT " . table_links . ".link_id FROM " . table_links . " WHERE ".table_links .".link_category=" .get_category_id("物") . " AND " . table_links . ".link_title LIKE '%".$_POST["key"]."%'" . " AND NOT EXISTS ( SELECT * FROM " . table_link_owner . " WHERE " . table_link_owner .".link_id = " . table_links . ".link_id)";
				$sqlquery = $sqlquery . " LIMIT $reco_offset,$top_users_size";
				$reco_lost_things = $db->get_col($sqlquery);
				$reco_lost_thing_link = new Link();
				$reco_output = '';
				if ($reco_lost_things) {
					foreach($reco_lost_things as $reco_lost_thing) {
						$reco_lost_thing_link->id = $reco_lost_thing;
						$reco_lost_thing_link->read();
						$reco_output .= $reco_lost_thing_link->print_summary_doing($doing, 0, 'short', true);	
					}
				}
				$main_smarty->assign('reco_user_page', $reco_output);
				$the_page = 'owner_hunt';
				$main_smarty->assign('reco_user_pagination', reco_do_pages($reco_rows, $top_users_size, $the_page, true));
			}	
			else {
				$main_smarty->assign('nothinghint','系统中没有此物');
			}
		}
	}
	
	$offset=(get_current_page()-1)*$top_users_size;
	$main_smarty->assign('cur_page',get_current_page());
	//get all links (things) without owner
	$sql = "SELECT COUNT(" . table_links . ".link_id) FROM " . table_links . " WHERE ".table_links .".link_category=" .get_category_id("物") . " AND NOT EXISTS ( SELECT * FROM " . table_link_owner . " WHERE " . table_link_owner .".link_id = " . table_links . ".link_id)";
	$rows = $db->get_var($sql);
	$sql = "SELECT " . table_links . ".link_id FROM " . table_links . " WHERE ".table_links .".link_category=" .get_category_id("物") . " AND NOT EXISTS ( SELECT * FROM " . table_link_owner . " WHERE " . table_link_owner .".link_id = " . table_links . ".link_id) LIMIT " . $offset . ", " . $top_users_size;
	//die($sql);
	$lost_things = $db->get_col($sql);
	$lost_thing_link = new Link();
	$output = '';
	if ($lost_things) {
		foreach($lost_things as $lost_thing) {
			$lost_thing_link->id = $lost_thing;
			$lost_thing_link->read();
			$output .= $lost_thing_link->print_summary_doing($doing, 0, 'short', true);	
		}
	}
	$main_smarty->assign('user_page', $output);
	$the_page = 'owner_hunt'; //indeed i feel this var is useless
	//$main_smarty->assign('user_pagination', do_pages($rows, $top_users_size, $the_page, true));
	$main_smarty->assign('user_pagination', submit_user_do_pages($rows, $top_users_size, $the_page, true));
	$main_smarty->assign('tpl_center', $the_template . '/humanhunt_owner_hunt');

	$main_smarty->display($the_template . '/pligg.tpl');
}

function user_hunt() {
	global $main_smarty, $db, $dblang, $current_user, $the_template, $top_users_size, $offset, $rows, $doing, $reco_offset, $reco_rows;
	
	//deal the search
	if (isset($_POST['key'])) {
		$main_smarty->assign('key',$_POST['key']);
		$main_smarty->assign('reco_cur_page',reco_get_current_page());
		if (trim($_POST['key']) != '') {
			$reco_offset=(reco_get_current_page()-1)*$top_users_size;
			$sqlquery = "SELECT COUNT(" . table_users . ".user_id) FROM " . table_users . " WHERE ".table_users .".user_first_time='true'" . " AND (user_names LIKE '%".$_POST["key"]."%' OR user_login LIKE '%".$_POST["key"]."%')";
			//die($sqlquery);
			$reco_rows = $db->get_var($sqlquery);
			if (!($reco_offset<$reco_rows)) {
				$reco_offset = 0;//in case the user change the keyword to search
				$main_smarty->assign('reco_cur_page',1);
				$_POST['reco_page'] = 1;//so will not get wrong location
			}
			if ($reco_rows>0) {
				$sqlquery = "SELECT " . table_users . ".* FROM " . table_users . " WHERE ".table_users .".user_first_time='true'" . " AND (user_names LIKE '%".$_POST["key"]."%' OR user_login LIKE '%".$_POST["key"]."%')";
				$sqlquery = $sqlquery . " LIMIT $reco_offset,$top_users_size";
				$searchsql = mysql_query($sqlquery);
				$reco_userlist = array();
				$submitter =  new User();
				while ($row = mysql_fetch_array ($searchsql, MYSQL_ASSOC)) array_push ($reco_userlist, $row);
				foreach($reco_userlist as $key => $val){
					$reco_userlist[$key]['Avatar'] = get_avatar('large', "", $val['user_login'], $val['user_email']);
					$owner_id = $reco_userlist[$key]['user_id'];
					$submitterinfo = $db->get_row("SELECT " .table_links. ".*" . " FROM " . table_links . ", " . table_link_owner . " WHERE " . table_link_owner . ".owner_id=" . $owner_id . " AND " . table_link_owner . ".link_id=" . table_links . ".link_id AND " . table_links . ".link_category=" . get_category_id('人'));
					$submitter->id = $submitterinfo->link_author;
					$submitter->read();
					$reco_userlist[$key]['submitter_id'] = $submitter->id;
					$reco_userlist[$key]['submitter_names'] = $submitter->names;
				}
				$main_smarty->assign('reco_userlist', $reco_userlist);
				$the_page = 'owner_hunt';
				$main_smarty->assign('reco_user_pagination', reco_do_pages($reco_rows, $top_users_size, $the_page, true));
			}	
			else {
				$main_smarty->assign('nothinghint','系统中没有此物');
			}
		}
	}
	
	$offset=(get_current_page()-1)*$top_users_size;
	$main_smarty->assign('cur_page',get_current_page());
	//get all links (things) without owner
	$sql = "SELECT COUNT(" . table_users . ".user_id) FROM " . table_users . " WHERE ".table_users .".user_first_time='true'";
	$rows = $db->get_var($sql);
	$sql = "SELECT " . table_users . ".* FROM " . table_users . " WHERE ".table_users .".user_first_time='true' LIMIT " . $offset . ", " . $top_users_size;
	//die($sql);
	$searchsql = mysql_query($sql);
	$userlist = array();
	$submitter =  new User();
	while ($row = mysql_fetch_array ($searchsql, MYSQL_ASSOC)) array_push ($userlist, $row);
	foreach($userlist as $key => $val){
		$userlist[$key]['Avatar'] = get_avatar('large', "", $val['user_login'], $val['user_email']);
		$owner_id = $userlist[$key]['user_id'];
		$submitterinfo = $db->get_row("SELECT " .table_links. ".*" . " FROM " . table_links . ", " . table_link_owner . " WHERE " . table_link_owner . ".owner_id=" . $owner_id . " AND " . table_link_owner . ".link_id=" . table_links . ".link_id AND " . table_links . ".link_category=" . get_category_id('人'));
		$submitter->id = $submitterinfo->link_author;
		$submitter->read();
		$userlist[$key]['submitter_id'] = $submitter->id;
		$userlist[$key]['submitter_names'] = $submitter->names;
	}
	$main_smarty->assign('userlist', $userlist);
	
	$the_page = 'owner_hunt'; //indeed I feel this var is useless
	$main_smarty->assign('user_pagination', submit_user_do_pages($rows, $top_users_size, $the_page, true));
	$main_smarty->assign('tpl_center', $the_template . '/humanhunt_user_hunt');

	$main_smarty->display($the_template . '/pligg.tpl');
}	

function edit_newhunt() {
	force_authentication();
	global $main_smarty, $db, $dblang, $current_user, $the_template;
	
	if (!isset($_POST['title'])) {//first time load
		$main_smarty->assign('randkey', rand(10000,10000000));
		$main_smarty->assign('tpl_center', $the_template . '/humanhunt_edit_newhunt');
		$main_smarty->display($the_template . '/pligg.tpl');
		die();
	}
	$deadline = unixtimestamp($_POST['orderdate']);
	if (($_POST['desc'] == '') || ($_POST['title'] == '') || (!time_diff(time(),$deadline))) {
		$main_smarty->assign('tags', $_POST['tags']);
		$main_smarty->assign('title', $_POST['title']);
		$main_smarty->assign('desc', $_POST['desc']);
		$main_smarty->assign('randkey', $_POST['randkey']);	
		$main_smarty->assign('orderdate', $_POST['orderdate']);
		$main_smarty->assign('private_info', $_POST['private_info']);
	
		if ($_POST['desc'] == '') {
				$main_smarty->assign('desccheck','请输入描述');
			}
		if ($_POST['title'] == '') {
				$main_smarty->assign('titlecheck','请输入标题');
			}
		if (!time_diff(time(),$deadline)) {
			$main_smarty->assign('deadlinecheck','请延长有效期');	
		}
		$main_smarty->assign('tpl_center', $the_template . '/humanhunt_edit_newhunt');
		$main_smarty->display($the_template . '/pligg.tpl');
		die();
	}
	
	$newhunt = new Hunt();
	$newhunt->userid = 0;
	$newhunt->linkid = 0;
	$newhunt->stage = "published";
	$newhunt->deadline = $deadline;
	$newhunt->private_info = $_POST['private_info'];
	$newhunt->store();
	$huntid = $newhunt->id;
	
	//$newlink = new Link();
	$newlink = new Link();
	$newlink->url = "hunt.php?hid=" . $huntid;
	$newlink->randkey = $_POST['randkey'];
	//$newlink->get($newlink->url);
	$newlink->valid = true;
	$newlink->category = get_category_id("hunt");
	$newlink->status='published';
	$newlink->published_date = time();
	$newlink->author=$current_user->user_id;
	$newlink->title = strip_tags(trim($_POST['title']));
	$newlink->title_url = makeUrlFriendly($newlink->title);
	$newlink->tags = tags_normalize_string(strip_tags(str_replace('，',',',trim($_POST['tags']))));
	$newlink->content = strip_tags(trim($_POST['desc']), Story_Content_Tags_To_Allow);
	$newlink->content = str_replace("\n", "<br />", $newlink->content);
	$newlink->link_summary = utf8_substr(strip_tags(trim($_POST['desc']), Story_Content_Tags_To_Allow), 0, StorySummary_ContentTruncate - 1);
	$newlink->link_summary = str_replace("\n", "<br />", $newlink->link_summary);		
	//$newlink->id = 0;
	
	$newlink->store();
	totals_adjust_count('published', 1);
	//$newlink->read(FALSE);
	
	tags_insert_string($newlink->id, $dblang, $newlink->tags);
	
	$newhunt->linkid = $newlink->id;
	$newhunt->store();
	header("Location: story.php?doing=view_hunt&id=" . $newlink->id);
}

function modify_hunt() {
	force_authentication();
	global $main_smarty, $db, $dblang, $current_user, $the_template;
	
	if (!isset($_POST['title'])) {//first time load
		$link = new Link();
		$link->id = $_REQUEST['linkid'];
		$link->read();
		$hunt = new Hunt();
		$hunt->linkid = $_REQUEST['linkid'];
		$hunt->read();
		$main_smarty->assign('linkid',$_REQUEST['linkid']);
		$main_smarty->assign('title',$link->title);
		$main_smarty->assign('tags',$link->tags);
		$main_smarty->assign('deadline',get_date_dmy($hunt->deadline));
		$main_smarty->assign('desc',$link->content);
		$main_smarty->assign('tpl_center', $the_template . '/humanhunt_modify_hunt');
		$main_smarty->display($the_template . '/pligg.tpl');
		die();
	}
	$deadline = unixtimestamp($_POST['orderdate']);
	if (($_POST['desc'] == '') || ($_POST['title'] == '') || (!time_diff(time(),$deadline))) {
		$main_smarty->assign('tags', $_POST['tags']);
		$main_smarty->assign('title', $_POST['title']);
		$main_smarty->assign('desc', $_POST['desc']);
		$main_smarty->assign('linkid', $_POST['linkid']);	
		$main_smarty->assign('deadline', $_POST['orderdate']);
	
		if ($_POST['desc'] == '') {
				$main_smarty->assign('desccheck','请输入描述');
			}
		if ($_POST['title'] == '') {
				$main_smarty->assign('titlecheck','请输入标题');
			}
		if (!time_diff(time(),$deadline)) {
			$main_smarty->assign('deadlinecheck','请延长有效期');	
		}
		$main_smarty->assign('tpl_center', $the_template . '/humanhunt_modify_hunt');
		$main_smarty->display($the_template . '/pligg.tpl');
		die();
	}
	
	$newhunt = new Hunt();
	$newhunt->linkid = $_POST['linkid'];
	$newhunt->read();
	$newhunt->deadline = $deadline;
	$newhunt->store();
	
	$linkres = new Link();
	$linkres->id = strip_tags($_POST['linkid']);
	$linkres->read();
	if($linkres->title != strip_tags(trim($_POST['title']))){
		$linkres->title = strip_tags(trim($_POST['title']));
		$linkres->title_url = makeUrlFriendly($linkres->title);
	}
	$linkres->content = strip_tags(trim($_POST['desc']), Story_Content_Tags_To_Allow);
	$linkres->content = str_replace("\n", "<br />", $linkres->content);
	$linkres->link_summary = utf8_substr(strip_tags(trim($_POST['desc']), Story_Content_Tags_To_Allow), 0, StorySummary_ContentTruncate - 1);
	$linkres->link_summary = str_replace("\n", "<br />", $linkres->link_summary);		
		
	$linkres->tags = tags_normalize_string(strip_tags(str_replace('，',',',trim($_POST['tags']))));
	tags_insert_string($linkres->id, $dblang, $linkres->tags);
	$linkres->store();
	
	header("Location: story.php?doing=view_hunt&id=" . $linkres->id);
}

function show_hunts(){
	header("Location: hunts_list.php");
}
?>
